﻿using Dapper;
using System.Data.SqlClient;
using yunbo.Model.BIP;
using yunbo.Model.BIQI;

namespace yunbo.Repositorys.BIQIRepositorys
{
	public class QMS_ZJBZRepository
	{
		public string data = "Data Source=121.37.93.71;Initial Catalog=FanXingMES;User Id=sa;Password=geili@2025;TrustServerCertificate=true;";


		/// <summary>
		/// 获取质检标准
		/// </summary>
		/// <param name="state"></param>
		/// <param name="str"></param>
		/// <returns></returns>
		public List<QMS_ZJBZ> GetQMS_ZJBZ(int state, string? str)
		{
			List<QMS_ZJBZ> zjbz = new List<QMS_ZJBZ>();

			using (SqlConnection connection = new SqlConnection(data))
			{
				string sql = @"select zjbz_id, zjbz_code, zjbz_name, 
(select dictionary_name from dictionary where dictionary_id=zjbz_type) zjbz_type_name, zjbz_type, 
zjbz_remark, zjbz_cp, zjbz_zjxm, zjbz_state
from [dbo].[qms_zjbz] where [zjbz_isdelete]=1 and [zjbz_state]=@state";
				if (str != null)
				{
					sql += @" and ([zjbz_code] like @str or [zjbz_name] like @str) ";
				}

				connection.Open();

				using (SqlCommand command = new SqlCommand(sql, connection))
				{
					command.Parameters.AddWithValue("@state", state);
					if (str != null)
					{
						command.Parameters.AddWithValue("@str", $"%{str}%");
					}

					using (SqlDataReader reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							zjbz.Add(new QMS_ZJBZ
							{
								zjbz_id = Convert.ToInt32(reader["zjbz_id"]),
								zjbz_code = reader["zjbz_code"].ToString(),
								zjbz_name = reader["zjbz_name"].ToString(),
								zjbz_type = Convert.ToInt32(reader["zjbz_type"]),
								zjbz_type_name = reader["zjbz_type_name"].ToString(),
								zjbz_cp = reader["zjbz_cp"].ToString(),
								zjbz_zjxm = reader["zjbz_zjxm"].ToString(),
								zjbz_remark = reader["zjbz_remark"].ToString(),
								zjbz_state = Convert.ToInt32(reader["zjbz_state"])
							});
						}
					}
				}
			}
			return zjbz;
		}


		/// <summary>
		/// 改变状态
		/// </summary>
		/// <param name="id"></param>
		/// <param name="state"></param>
		/// <returns></returns>
		public bool StateChange(int id, int state)
		{
			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					string sql = @"update [dbo].[qms_zjbz] set [zjbz_state]=@State where [zjbz_id]=@Id";
					return connection.Execute(sql, new { Id = id, State = state }) > 0;
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"状态更改失败: {ex.Message}");
				return false;
			}
		}


		/// <summary>
		/// 新增
		/// </summary>
		/// <param name="zjbz"></param>
		/// <returns></returns>
		public bool AddQMS_ZJBZ(QMS_ZJBZ zjbz)
		{
			string sql = @"insert into [dbo].[qms_zjbz]
(zjbz_code, zjbz_name, zjbz_type, zjbz_remark, zjbz_cp, zjbz_zjxm,zjbz_create_by)
values 
(@code,@name,@type,@remark,@cp,@zjxm,@dw,1);";

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (SqlCommand command = new SqlCommand(sql, connection))
					{
						command.Parameters.AddWithValue("@code", zjbz.zjbz_code);
						command.Parameters.AddWithValue("@name", zjbz.zjbz_name);
						command.Parameters.AddWithValue("@type", zjbz.zjbz_type);
						command.Parameters.AddWithValue("@remark", zjbz.zjbz_remark);
						command.Parameters.AddWithValue("@cp", zjbz.zjbz_cp);
						command.Parameters.AddWithValue("@zjxm", zjbz.zjbz_zjxm);

						int rowsAffected = command.ExecuteNonQuery();
						return rowsAffected > 0; // 如果插入成功，返回 true
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志或处理异常
				Console.WriteLine("An error occurred: " + ex.Message);
				return false; // 如果发生异常，返回 false
			}
		}


		/// <summary>
		/// 修改
		/// </summary>
		/// <param name="zjbz"></param>
		/// <returns></returns>
		public bool UpdateQMS_ZJBZ(QMS_ZJBZ zjbz)
		{
			string sql = @"update [dbo].[qms_zjbz] set
zjbz_name=@name, zjbz_type=@type, zjbz_remark=@remark, zjbz_cp=@cp, zjbz_zjxm=@zjxm,
[zjbz_update_by]=1,[zjbz_update_time]=GETDATE()
where [zjbz_id]=@id";

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (SqlCommand command = new SqlCommand(sql, connection))
					{
						command.Parameters.AddWithValue("@name", zjbz.zjbz_name);
						command.Parameters.AddWithValue("@type", zjbz.zjbz_type);
						command.Parameters.AddWithValue("@remark", zjbz.zjbz_remark);
						command.Parameters.AddWithValue("@cp", zjbz.zjbz_cp);
						command.Parameters.AddWithValue("@zjxm", zjbz.zjbz_zjxm);
						command.Parameters.AddWithValue("@id", zjbz.zjbz_id);

						int rowsAffected = command.ExecuteNonQuery();
						return rowsAffected > 0; // 如果插入成功，返回 true
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志或处理异常
				Console.WriteLine("An error occurred: " + ex.Message);
				return false; // 如果发生异常，返回 false
			}
		}


		/// <summary>
		/// 删除
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public bool DelQMS_ZJBZ(int id)
		{
			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					string sql = @"UPDATE [dbo].[qms_zjbz] 
                       SET zjbz_isdelete = 0 
                       WHERE zjbz_id = @Id";

					return connection.Execute(sql, new { Id = id }) > 0;
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"删除失败: {ex.Message}");
				return false;
			}
		}


		/// <summary>
		/// 批量删除
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		public bool DelQMS_ZJBZs(int[] ids)
		{
			// 参数验证
			if (ids == null || ids.Length == 0)
				return false;

			try
			{
				using (SqlConnection connection = new SqlConnection(data))
				{
					connection.Open();
					using (var transaction = connection.BeginTransaction()) // 添加事务
					{
						try
						{
							string sql = @"UPDATE [dbo].[qms_zjbz] 
		                                 SET zjbz_isdelete = 0 
		                                 WHERE zjbz_id IN @Ids";

							int affectedRows = connection.Execute(sql, new { Ids = ids }, transaction);
							transaction.Commit(); // 提交事务

							// 确保所有ID都成功更新
							return affectedRows == ids.Length;
						}
						catch
						{
							transaction.Rollback(); // 回滚事务
							throw;
						}
					}
				}
			}
			catch (Exception ex)
			{
				// 记录日志等异常处理
				Console.WriteLine($"批量删除失败: {ex.Message}");
				return false;
			}
		}
	}
}
